import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: rmikhaylenko mirusnet@gmail.com
 * Date: 14/08/13
 * Time: 09:17
 */
public class ReadInThread extends Thread {
    private final Process process;
    private final String playlistPath;
    private final int fileCount;
    private final int startPosition;


    public ReadInThread(Process process, String playlistPath, int startPosition, int fileCount) {
        this.process = process;
        this.playlistPath = playlistPath;
        this.startPosition = startPosition;
        this.fileCount = fileCount;

    }

    @Override
    public void run() {
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String seconds_pattern = "ANS_time_pos";
        String exit_pattern = "Exiting... \\(End of file\\)";
        String quit_pattern = "Exiting... \\(Quit\\)";

        Pattern seconds_pattern_compiled = Pattern.compile(seconds_pattern);
        Pattern exit_pattern_compiled = Pattern.compile(exit_pattern);
        Pattern quit_pattern_compiled = Pattern.compile(quit_pattern);

        String line;
        try {
            while ((line = br.readLine()) != null) {
                Matcher seconds_pattern_matcher = seconds_pattern_compiled.matcher(line);
                Matcher exit_pattern_matcher = exit_pattern_compiled.matcher(line);
                Matcher quit_pattern_matcher = quit_pattern_compiled.matcher(line);

                if (seconds_pattern_matcher.find()) {
                    PlaylistUtils.changeSecondsAndTrackInPlaylist(PlaylistUtils.parseSeconds(line), startPosition, playlistPath);
                } else if (exit_pattern_matcher.find()) {
                    PlaylistUtils.changeSecondsAndTrackInPlaylist("0", (startPosition == fileCount ? 1 : startPosition+1), playlistPath);
                } else if (quit_pattern_matcher.find()) {
                    ButtonAction.quit = true;
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
